<template>
  <view class="resume-edit-container">
    <!-- 内容容器（添加内边距避免被底部按钮遮挡） -->
    <view class="content-wrapper">
      <!-- 头像区域 -->
      <view class="avatar-section">
        <image class="avatar" :src="editData.avatar || '/static/logo.png'"></image>
        <text class="change-avatar" @click="changeAvatar">点击更换头像</text>
      </view>
      
      <!-- 表单区域 -->
      <form class="form-section">
        <!-- 基本信息 -->
        <view class="form-item">
          <text class="label required">姓名</text>
          <input class="input" v-model="editData.name" placeholder="请输入姓名" />
        </view>
        
        <view class="form-item">
          <text class="label required">在读状态</text>
          <picker mode="selector" :range="statusList" v-model="statusIndex">
            <view class="picker-view">{{ statusList[statusIndex] }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label required">性别</text>
          <picker mode="selector" :range="genderList" v-model="genderIndex">
            <view class="picker-view">{{ genderList[genderIndex] }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label required">学历</text>
          <picker mode="selector" :range="educationList" v-model="educationIndex">
            <view class="picker-view">{{ educationList[educationIndex] }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label required">电话</text>
          <input class="input" v-model="editData.phone" type="number" placeholder="请输入电话" />
        </view>
        
        <view class="form-item">
          <text class="label">邮箱</text>
          <input class="input" v-model="editData.email" type="email" placeholder="请输入邮箱" />
        </view>
        
        <!-- 个人优势 -->
        <view class="form-item">
          <text class="label">个人优势</text>
          <textarea class="textarea" v-model="editData.personalAdvantage" placeholder="请描述你的核心优势"></textarea>
        </view>
        
        <!-- 期望岗位 -->
        <view class="form-item">
          <text class="label">期望地区</text>
          <input class="input" v-model="editData.jobRegion" placeholder="如：北京/上海/广州" />
        </view>
        
        <view class="form-item">
          <text class="label">期望岗位</text>
          <input class="input" v-model="editData.desiredPosition" placeholder="如：前端开发工程师" />
        </view>
        
        <view class="form-item">
          <text class="label">期望薪资</text>
          <view class="salary-group">
            <input class="input salary-input" v-model="editData.minSalary" placeholder="最低" />
            <text class="salary-separator">-</text>
            <input class="input salary-input" v-model="editData.maxSalary" placeholder="最高" />
            <text class="salary-unit">K/月</text>
          </view>
        </view>
        
        <!-- 教育经历 -->
        <view class="section-title">教育经历 <text class="required-tag">必填</text></view>
        
        <view class="form-item">
          <text class="label required">时间范围</text>
          <input class="input" v-model="editData.educationTime" placeholder="如：2020-09 - 2024-06" />
        </view>
        
        <view class="form-item">
          <text class="label required">学校及专业</text>
          <input class="input" v-model="editData.educationSchoolMajor" placeholder="如：XX大学 - 计算机科学与技术" />
        </view>
        
        <view class="form-item">
          <text class="label">主修课程</text>
          <textarea class="textarea" v-model="editData.educationCourse" placeholder="如：数据结构、操作系统"></textarea>
        </view>
        
        <!-- 社团经历 -->
        <view class="form-item">
          <text class="label">社团/组织经历</text>
          <textarea class="textarea" v-model="editData.organizationExperience" placeholder="如：担任学生会宣传部部长"></textarea>
        </view>
        
        <!-- 专业技能 -->
        <view class="form-item">
          <text class="label">专业技能及证书</text>
          <textarea class="textarea" v-model="editData.professionalSkills" placeholder="如：1. 熟练掌握Java；2. 英语六级"></textarea>
        </view>
        
        <!-- 工作/实习经历 -->
        <view class="section-title">工作/实习经历</view>
        
        <view v-for="(item, index) in editData.workExperiences" :key="index" class="experience-group">
          <view class="form-item">
            <text class="label">时间范围</text>
            <input class="input" v-model="item.time" placeholder="如：2023-07 - 2023-09" />
          </view>
          
          <view class="form-item">
            <text class="label">公司及职位</text>
            <input class="input" v-model="item.position" placeholder="如：XX科技 - 前端开发实习生" />
          </view>
          
          <view class="form-item">
            <text class="label">工作内容</text>
            <textarea class="textarea" v-model="item.content" placeholder="请描述工作内容及成果"></textarea>
          </view>
          
          <view v-if="editData.workExperiences.length > 1" class="delete-btn" @click="deleteWorkExperience(index)">
            <text>删除此经历</text>
          </view>
        </view>
        
        <view class="add-btn" @click="addWorkExperience">+ 添加工作/实习经历</view>
        
        <!-- 项目经历 -->
        <view class="section-title">项目经历</view>
        
        <view v-for="(project, index) in editData.projects" :key="index" class="experience-group">
          <view class="form-item">
            <text class="label">时间范围</text>
            <input class="input" v-model="project.time" placeholder="如：2023-03 - 2023-06" />
          </view>
          
          <view class="form-item">
            <text class="label">项目名称</text>
            <input class="input" v-model="project.name" placeholder="如：校园在线商城系统" />
          </view>
          
          <view class="form-item">
            <text class="label">项目描述</text>
            <textarea class="textarea" v-model="project.description" placeholder="请描述项目内容及成果"></textarea>
          </view>
          
          <view v-if="editData.projects.length > 1" class="delete-btn" @click="deleteProject(index)">
            <text>删除此项目</text>
          </view>
        </view>
        
        <view class="add-btn" @click="addProject">+ 添加项目经历</view>
        
        <!-- 底部留白（额外增加，确保最后内容不被按钮遮挡） -->
        <view class="bottom-space"></view>
      </form>
    </view>
    
    <!-- 固定底部的保存按钮 -->
    <view class="save-bar">
      <view class="save-btn" @click="saveEdit">保存</view>
    </view>
  </view>
</template>

<script>
import { getOnlineResume, updateOnlineResume, addOnlineResume } from "@/api/onlineResume.js";

export default {
  data() {
    return {
      // 编辑数据对象
      editData: {
        avatar: '',
        name: '',
        phone: '',
        email: '',
        personalAdvantage: '',
        jobRegion: '',
        desiredPosition: '',
        minSalary: '',
        maxSalary: '',
        educationTime: '',
        educationSchoolMajor: '',
        educationCourse: '',
        organizationExperience: '',
        professionalSkills: '',
        workExperiences: [{ time: '', position: '', content: '' }],
        projects: [{ time: '', name: '', description: '' }]
      },
      // 选择器数据
      statusList: ['在校生', '应届毕业生', '已毕业'],
      genderList: ['女', '男'],
      educationList: ['高中', '大专', '本科', '硕士', '博士', '其他'],
      // 选择器索引
      statusIndex: 0,
      genderIndex: 0,
      educationIndex: 2, // 默认本科
      // 表单ID
      ruleForm: {
        id: null
      }
    };
  },
  onLoad() {
    this.fetchResumeData();
  },
  methods: {
    // 获取简历数据
    async fetchResumeData() {
      try {
        const response = await getOnlineResume();
        const data = response.data;
        
        this.ruleForm.id = data.id;
        
        // 填充数据
        this.editData = {
          ...this.editData,
          avatar: data.avatar || '',
          name: data.username || '',
          phone: data.phone || '',
          email: data.email || '',
          personalAdvantage: data.introduction || '',
          desiredPosition: data.desiredPosition || '',
          jobRegion: data.jobRegion || '',
          minSalary: data.minSalary || '',
          maxSalary: data.maxSalary || '',
          educationTime: this.formatTime(data.eduExpsList?.[0]?.startTime, data.eduExpsList?.[0]?.endTime),
          educationSchoolMajor: this.formatSchoolMajor(data.eduExpsList?.[0]?.schoolName, data.eduExpsList?.[0]?.major),
          educationCourse: data.eduExpsList?.[0]?.mainCourse || '',
          organizationExperience: data.eduExpsList?.[0]?.schoolExperience || '',
          professionalSkills: data.professionalSkills || '',
          workExperiences: data.workExpsList?.map(item => ({
            time: this.formatTime(item.startTime, item.endTime),
            position: `${item.companyName || ''} - ${item.positionName || ''}`,
            content: item.workContent || ''
          })) || [{ time: '', position: '', content: '' }],
          projects: data.proExpsList?.map(item => ({
            time: this.formatTime(item.proStartTime, item.proEndTime),
            name: item.proName || '',
            description: item.proDesc || ''
          })) || [{ time: '', name: '', description: '' }]
        };
        
        // 设置选择器索引
        this.statusIndex = data.studyStatus === 0 ? 0 : data.studyStatus === 1 ? 1 : 2;
        this.genderIndex = data.sex === 1 ? 0 : 0; // 默认女
        this.educationIndex = this.educationList.indexOf(data.education) || 2;
        
      } catch (error) {
        console.error('获取简历数据失败:', error);
        uni.showToast({ title: '获取数据失败', icon: 'none' });
      }
    },
    // 格式化时间
    formatTime(start, end) {
      return `${start || ''} - ${end || ''}`;
    },
    // 格式化学校专业
    formatSchoolMajor(school, major) {
      return `${school || ''} - ${major || ''}`;
    },
    // 更换头像
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.editData.avatar = res.tempFilePaths[0];
        }
      });
    },
    // 工作经历操作
    addWorkExperience() {
      this.editData.workExperiences.push({ time: '', position: '', content: '' });
    },
    deleteWorkExperience(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除此经历吗？',
        success: (res) => {
          if (res.confirm) this.editData.workExperiences.splice(index, 1);
        }
      });
    },
    // 项目经历操作
    addProject() {
      this.editData.projects.push({ time: '', name: '', description: '' });
    },
    deleteProject(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除此项目吗？',
        success: (res) => {
          if (res.confirm) this.editData.projects.splice(index, 1);
        }
      });
    },
    // 保存编辑
    async saveEdit() {
      // 验证
      if (!this.editData.name) return uni.showToast({ title: '请输入姓名', icon: 'none' });
      if (!this.editData.phone) return uni.showToast({ title: '请输入电话', icon: 'none' });
      if (!this.editData.educationTime) return uni.showToast({ title: '请输入教育经历时间', icon: 'none' });
      if (!this.editData.educationSchoolMajor) return uni.showToast({ title: '请输入学校及专业', icon: 'none' });
      
      // 构造提交数据
      const submitData = {
        id: this.ruleForm.id,
        username: this.editData.name,
        avatar: this.editData.avatar,
        studyStatus: this.statusIndex,
        sex: this.genderIndex,
        education: this.educationList[this.educationIndex],
        phone: this.editData.phone,
        email: this.editData.email,
        introduction: this.editData.personalAdvantage,
        jobRegion: this.editData.jobRegion,
        desiredPosition: this.editData.desiredPosition,
        minSalary: this.editData.minSalary,
        maxSalary: this.editData.maxSalary,
        eduExpsList: [{
          startTime: this.editData.educationTime.split(' - ')[0] || '',
          endTime: this.editData.educationTime.split(' - ')[1] || '',
          schoolName: this.editData.educationSchoolMajor.split(' - ')[0] || '',
          major: this.editData.educationSchoolMajor.split(' - ')[1] || '',
          mainCourse: this.editData.educationCourse,
          schoolExperience: this.editData.organizationExperience
        }],
        workExpsList: this.editData.workExperiences.map(item => ({
          startTime: item.time.split(' - ')[0] || '',
          endTime: item.time.split(' - ')[1] || '',
          companyName: item.position.split(' - ')[0] || '',
          positionName: item.position.split(' - ')[1] || '',
          workContent: item.content
        })),
        proExpsList: this.editData.projects.map(item => ({
          proStartTime: item.time.split(' - ')[0] || '',
          proEndTime: item.time.split(' - ')[1] || '',
          proName: item.name,
          proDesc: item.description
        }))
      };
      
      try {
        uni.showLoading({ title: '保存中...' });
        
        if (this.ruleForm.id) {
          await updateOnlineResume(submitData);
          uni.showToast({ title: '更新成功', icon: 'success' });
        } else {
          await addOnlineResume(submitData);
          uni.showToast({ title: '保存成功', icon: 'success' });
        }
        
        uni.hideLoading();
        setTimeout(() => uni.navigateBack(), 1500);
        
      } catch (error) {
        uni.hideLoading();
        console.error('保存失败:', error);
        uni.showToast({ title: '保存失败，请重试', icon: 'none' });
      }
    }
  }
};
</script>

<style scoped>
.resume-edit-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  position: relative;
  padding-bottom: 100rpx; /* 预留底部按钮高度 */
}

/* 内容容器 - 添加20rpx外边距 */
.content-wrapper {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

/* 底部保存按钮栏 */
.save-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999; /* 确保在最上层显示 */
}

.save-btn {
  width: calc(100% - 40rpx); /* 减去左右边距，避免超出屏幕 */
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  background-color: #409eff;
  color: white;
  border-radius: 10rpx;
  font-size: 30rpx;
  font-weight: 500;
  opacity: 1; /* 明确设置不透明 */
  margin: 0 auto; /* 居中显示 */
}
  
  /* 头像区域 */
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
  }
  
  .avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    margin-bottom: 20rpx;
    border: 2rpx solid #eee;
  }
  
  .change-avatar {
    color: #409eff;
    font-size: 26rpx;
  }
  
  /* 表单区域 */
  .form-section {
    padding: 0 30rpx;
  }
  
  .form-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
  }
  
  .label {
    width: 200rpx;
    font-size: 28rpx;
    color: #333;
  }
  
  .required::before {
    content: "*";
    color: #f56c6c;
    margin-right: 5rpx;
  }
  
  .input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    padding-left: 20rpx;
  }
  
  .textarea {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    padding: 20rpx 0 0 20rpx;
    min-height: 140rpx;
  }
  
  .picker-view {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    padding-left: 20rpx;
    text-align: left;
  }
  
  /* 薪资输入区域 */
  .salary-group {
    flex: 1;
    display: flex;
    align-items: center;
    padding-left: 20rpx;
  }
  
  .salary-input {
    width: 160rpx;
    text-align: center;
    padding: 0 10rpx;
    border: 1rpx solid #eee;
    border-radius: 6rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
  }
  
  .salary-separator {
    margin: 0 15rpx;
    color: #999;
  }
  
  .salary-unit {
    margin-left: 15rpx;
    color: #999;
  }
  
  /* 标题区域 */
  .section-title {
    padding: 30rpx 0 20rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #2c3e50;
  }
  
  .required-tag {
    color: #f56c6c;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  
  /* 经历组 */
  .experience-group {
    margin-bottom: 30rpx;
    padding-bottom: 30rpx;
    border-bottom: 1rpx dashed #eee;
  }
  
  .delete-btn {
    color: #f56c6c;
    font-size: 26rpx;
    text-align: center;
    padding: 20rpx 0;
  }
  
  .add-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border: 2rpx dashed #409eff;
    border-radius: 10rpx;
    color: #409eff;
    font-size: 28rpx;
    margin: 30rpx 0;
  }
  
  /* 底部留白（确保最后内容不被底部按钮遮挡） */
  .bottom-space {
    height: 40rpx;
  }
  </style>